package com.sig;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;

/**
 * JDK8新特性
 * 
 * @author sig
 * @since 2016-6-8 14:35:44
 */
public class Jdk8Test {

	/**
	 * 1、接口的默认方法default(扩展方法)
	 */
	public void defaultTest() {
		Formula f = new Formula() {

			@Override
			public double calculate(int a) {
				return sqrt(a * 100);
			}
		};
		print(f.calculate(100));
		print(f.sqrt(16));
	}

	/**
	 * 2、Lambda表达式
	 */
	public void lambdaTest() {
		List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

		// 旧版本排序
		// Collections.sort(names, new Comparator<String>() {
		//
		// @Override
		// public int compare(String o1, String o2) {
		// return o2.compareTo(o1);
		// }
		// });

		Collections.sort(names, (a, b) -> b.compareTo(a));
	}

	/**
	 * 3、函数式接口
	 */
	public void functionalInterfaceTest() {
		Converter<String, Integer> converter = from -> Integer.valueOf(from);
		print(converter.convert("123"));
	}

	/**
	 * 4、方法与构造函数引用
	 */
	public void methodAndConstructorReferenceTest() {
		Converter<String, Integer> converter = Integer::valueOf;
		print(converter.convert("123"));

		PersonFactory<Person> pf = Person::new;
		print(pf.create("Perter", "Parker"));

		int num = 1;// 局部变量num隐性具有final语义
		Converter<Integer, String> stringConverter1 = (from) -> String.valueOf(from + num);
		print(stringConverter1.convert(2));

		Converter<Integer, String> stringConverter2 = new Converter<Integer, String>() {

			@Override
			public String convert(Integer from) {
				return String.valueOf(from + num);
			}
		};
		print(stringConverter2.convert(2));
	}

	/**
	 * 5、Predicate 接口
	 */
	public void predicateTest() {
		Predicate<String> predicate = (s) -> s.length() > 0;

		print(predicate.test("foo"));
		print(predicate.negate().test("foo"));
		// Predicate<Boolean> nonNull = Objects::nonNull;
		// Predicate<Boolean> isNull = Objects::isNull;
		// Predicate<String> isEmpty = String::isEmpty;
		// Predicate<String> isNotEmpty = isEmpty.negate();
	}

	/**
	 * 6、Function 接口
	 */
	public void functionTest() {
		Function<String, Integer> toInteger = Integer::valueOf;
		Function<String, Object> back2String = toInteger.andThen(String::valueOf);
		print(back2String.apply("123") instanceof String);
	}

	/**
	 * 7、Supplier 接口
	 */
	public void supplierTest() {
		Supplier<Person> personSupplier = Person::new;
		personSupplier.get(); // new Person
	}

	/**
	 * 8、Consumer 接口
	 */
	public void consumerTest() {
		Consumer<Person> greeter = p -> print("Hello," + p.getFirstName());
		greeter.accept(new Person("Luke", "Skywalker"));
	}

	/**
	 * 9、Comparator 接口
	 */
	public void comparatorTest() {
		Comparator<Person> comparator = (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName());
		Person p1 = new Person("John", "Doe");
		Person p2 = new Person("Alice", "Wonderland");
		comparator.compare(p1, p2); // > 0
		comparator.reversed().compare(p1, p2); // < 0
	}

	/**
	 * 10、Optional 接口
	 */
	public void optionalTest() {
		Optional<String> optional = Optional.of("bam");
		print(optional.isPresent());
		print(optional.get());
		print(optional.orElse("fallback"));
		optional.ifPresent(s -> print(s.charAt(0)));
	}

	/**
	 * 11、Stream 接口
	 */
	public void streamTest() {
		List<String> stringCollection = new ArrayList<>();
		stringCollection.add("ddd2");
		stringCollection.add("aaa2");
		stringCollection.add("bbb1");
		stringCollection.add("aaa1");
		stringCollection.add("bbb3");
		stringCollection.add("ccc");
		stringCollection.add("bbb2");
		stringCollection.add("ddd1");

		// Filter 过滤
		stringCollection.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);

		// Sort 排序
		stringCollection.stream().sorted().filter(s -> s.startsWith("a")).forEach(System.out::println);

		// Map 映射
		stringCollection.stream().map(String::toUpperCase).sorted((a, b) -> b.compareTo(a))
				.forEach(System.out::println);

		// Match 匹配
		boolean anyStartsWithA = stringCollection.stream().anyMatch(s -> s.startsWith("a"));
		print(anyStartsWithA); // true
		boolean allStartsWithA = stringCollection.stream().allMatch(s -> s.startsWith("a"));
		print(allStartsWithA); // false
		boolean noneStartsWithZ = stringCollection.stream().noneMatch(s -> s.startsWith("z"));
		print(noneStartsWithZ); // true

		// Count 计数
		long startsWithB = stringCollection.stream().filter(s -> s.startsWith("b")).count();
		print(startsWithB); // 3

		// Reduce 规约
		Optional<String> reduced = stringCollection.stream().sorted().reduce((s1, s2) -> s1 + "#" + s2);
		reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"

		// 并行 Stream
		// int max = 1000000;
		// List<String> values = new ArrayList<>(max);
		// for (int i = 0; i < max; i++) {
		// UUID uuid = UUID.randomUUID();
		// values.add(uuid.toString());
		// }

		// 串行排序
		// long t0 = System.nanoTime();
		// long count = values.stream().sorted().count();
		// print(count);
		// long t1 = System.nanoTime();
		// long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
		// print(String.format("sequential sort took: %d ms",
		// millis));

		// 并行排序
		// long t0 = System.nanoTime();
		// long count = values.parallelStream().sorted().count();
		// print(count);
		// long t1 = System.nanoTime();
		// long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
		// print(String.format("parallel sort took: %d ms",
		// millis));

		// Map
		Map<Integer, String> map = new HashMap<>();
		for (int i = 0; i < 10; i++) {
			map.putIfAbsent(i, "val" + i);
		}
		map.forEach((id, val) -> print(val));

		map.computeIfPresent(3, (num, val) -> val + num);
		map.get(3); // val33
		map.computeIfPresent(9, (num, val) -> null);
		map.containsKey(9); // false
		map.computeIfAbsent(23, num -> "val" + num);
		map.containsKey(23); // true
		map.computeIfAbsent(3, num -> "bam");
		map.get(3); // val33

		map.remove(3, "val3");
		map.get(3); // val33
		map.remove(3, "val33");
		map.get(3); // null

		map.getOrDefault(42, "not found"); // not found

		map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
		map.get(9); // val9
		map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
		map.get(9); // val9concat
	}

	/**
	 * 12、Date API
	 */
	public void dateApiTest() {
		// Clock clock = Clock.systemDefaultZone();
		// long millis = clock.millis(); // 等同于System.currentTimeMillis();
		// Instant instant = clock.instant();
		// Date legacyDate = Date.from(instant); // legacy java.util.Date

		// Timezones 时区
		print(ZoneId.getAvailableZoneIds());
		// prints all available timezone ids
		ZoneId zone1 = ZoneId.of("Europe/Berlin");
		ZoneId zone2 = ZoneId.of("Brazil/East");
		print(zone1.getRules());// ZoneRules[currentStandardOffset=+01:00]
		print(zone2.getRules());// ZoneRules[currentStandardOffset=-03:00]

		// LocalTime 本地时间
		LocalTime now1 = LocalTime.now(zone1);
		LocalTime now2 = LocalTime.now(zone2);
		print(now1.isBefore(now2)); // false
		long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
		long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
		print(hoursBetween); // -4
		print(minutesBetween); // -299

		// 解析时间字符串
		// LocalTime late = LocalTime.of(23, 59, 59);
		// print(late); // 23:59:59
		// DateTimeFormatter germanFormatter =
		// DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
		// .withLocale(Locale.GERMAN);
		// LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
		// print(leetTime); // 13:37

		// LocalDate 本地日期
		// LocalDate today = LocalDate.now();
		// LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
		// LocalDate yesterday = tomorrow.minusDays(2);
		// LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
		// DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
		// print(dayOfWeek);

		DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
				.withLocale(Locale.GERMAN);
		LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
		System.out.println(xmas); // 2014-12-24

		// LocalDateTime 本地日期时间
		LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
		DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
		print(dayOfWeek); // WEDNESDAY
		Month month = sylvester.getMonth();
		print(month); // DECEMBER
		long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
		print(minuteOfDay); // 1439

		Instant instant = sylvester.atZone(ZoneId.systemDefault()).toInstant();
		Date legacyDate = Date.from(instant);
		print(legacyDate); // Wed Dec 31 23:59:59 CET 2014

		// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd,
		// yyyy - HH:mm");
		// LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13",
		// formatter);
		// String string = formatter.format(parsed);
		// print(string); // Nov 03, 2014 - 07:13
	}

	/**
	 * 13、Annotation 注解
	 */
	@Test
	public void annotationTest() {
		// Hint hint = Person.class.getAnnotation(Hint.class);
		// print(hint); // null
		// Hints hints1 = Person.class.getAnnotation(Hints.class);
		// print(hints1.value().length); // 2
		// Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
		// print(hints2.length); // 2
	}

	public static void print(Object o) {
		System.out.println(o);
	}
}
